package model.webService;

import java.net.SocketException;

import android.util.Log;
import view.ArgusActivity;

public class ConnectionHandler 
{
	private final String TAG = ConnectionHandler.class.getSimpleName();
	
	private ClientThread client;
	
	public ConnectionHandler()
	{}
	
		
	public void connectToServer(ArgusActivity activity)
	{
		client = new ClientThread(activity);
		new Thread(client).start();
	}

	public void disconnectFromServer()
	{		
		sendSocketCall("", Command.Logout);
		client.deleteSocket();
	}	
	
	/**
	 * Sends a call to the web service asking for a specific snippet.
	 * @param id The Id of requested snippet.
	 * @deprecated This method is no longer used.
	 */
	public void getSnippet(String id)
	{
		sendSocketCall(id, Command.getSnippet);
	}

	/**
	 * Sends calls to the web service regarding subscriptions.
	 * @param subscribeIds A string that holds Id's of snippets to which to subscribe.  
	 * @param unSubscribeIds A string that holds Id's of snippets to which to unsubscribe.
	 */
	public void handleSubscriptions(String subscribeIds, String unSubscribeIds) 
	{
		if(!unSubscribeIds.trim().isEmpty())
		{
			Log.i(TAG, String.format("Unsubscribed: %s", unSubscribeIds));
			sendSocketCall(unSubscribeIds, Command.Unsubscribe);
		}
		
		if(!subscribeIds.trim().isEmpty())
		{
			Log.i(TAG, String.format("Subscribed: %s", subscribeIds));
			sendSocketCall(subscribeIds, Command.Subscribe);
		}
	}
	
	/**
	 * Sends a call to the web service.
	 * @param msg The message to send along with the call.
	 * @param command The command to indicate the purpose of the call.
	 */
	private void sendSocketCall(String msg, Command command)
	{
		try 
		{
			client.sendSocketCall(msg, command);			
		} 
		catch (SocketException e) 
		{
			client.handleLostConnection();
			e.printStackTrace();
		}
	}

	public void setActivity(ArgusActivity observer) 
	{
		client.setActivity(observer);		
	}
}
